<template>
  <div class="photographer-list">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h2>摄影师列表</h2>
      <button @click="$router.push('/photographer-map')" style="padding: 6px 18px; background: #409EFF; color: #fff; border: none; border-radius: 4px; cursor: pointer;">地图查看</button>
    </div>
    <div class="page-header">
      <p>选择您心仪的摄影师，开始您的拍摄之旅</p>
    </div>

    <!-- 热门摄影师展示区 -->
    <div v-if="hotPhotographers.length" class="hot-photographers" style="margin-bottom: 24px;">
      <h3 style="margin-bottom: 12px;">热门摄影师</h3>
      <el-row :gutter="20">
        <el-col :span="6" v-for="photographer in hotPhotographers" :key="photographer.id">
          <el-card class="hot-photographer-card" @click="goToDetail(photographer.id)">
            <img :src="photographer.avatar || 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200&h=200&fit=crop&crop=face'" class="hot-photographer-avatar" />
            <div style="margin-top: 8px; font-weight: bold;">{{ photographer.name }}</div>
            <div style="color: #888; font-size: 13px;">完成订单数：{{ photographer.orderCount }}</div>
            <div style="color: #888; font-size: 13px;">风格：{{ photographer.style }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.style" placeholder="拍摄风格" clearable>
            <el-option label="婚纱" value="婚纱" />
            <el-option label="写真" value="写真" />
            <el-option label="纪实" value="纪实" />
            <el-option label="人像" value="人像" />
            <el-option label="商业" value="商业" />
            <el-option label="广告" value="广告" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.workYears" placeholder="工作年限" clearable>
            <el-option label="1-3年" value="1-3" />
            <el-option label="3-5年" value="3-5" />
            <el-option label="5年以上" value="5+" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.authStatus" placeholder="认证状态" clearable>
            <el-option label="已认证" :value="1" />
            <el-option label="未认证" :value="0" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 摄影师列表 -->
    <div class="photographers-grid">
      <el-row :gutter="20">
        <el-col :span="8" v-for="photographer in filteredPhotographers" :key="photographer.id">
          <el-card class="photographer-card" @click="goToDetail(photographer.id)">
            <div class="photographer-header">
              <img :src="photographer.avatar || 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200&h=200&fit=crop&crop=face'" class="photographer-avatar" />
              <div class="photographer-info">
                <h3>{{ photographer.name }}</h3>
                <el-tag :type="photographer.authStatus === 1 ? 'success' : 'info'" size="small">
                  {{ photographer.authStatus === 1 ? '已认证' : '未认证' }}
                </el-tag>
              </div>
            </div>
            
            <div class="photographer-details">
              <p class="photographer-style">
                <el-icon><Camera /></el-icon>
                {{ photographer.style }}
              </p>
              <p class="photographer-years">
                <el-icon><Timer /></el-icon>
                工作{{ photographer.workYears }}年
              </p>
              <p class="photographer-phone">
                <el-icon><Phone /></el-icon>
                {{ photographer.phone }}
              </p>
              <p class="photographer-intro">{{ photographer.intro }}</p>
              <p class="photographer-available">
                <el-icon><Calendar /></el-icon>
                档期: {{ photographer.availableSchedule }}
              </p>
              <p class="photographer-auth">
                <el-tag :type="getAuthStatusType(photographer.authStatus)">
                  {{ getAuthStatusText(photographer.authStatus) }}
                </el-tag>
              </p>
              <p class="photographer-create">
                创建: {{ photographer.createTime }}
              </p>
              <p class="photographer-update">
                更新: {{ photographer.updateTime }}
              </p>
            </div>
            
            <div class="photographer-footer">
              <el-button type="primary" size="small" @click.stop="handleBook(photographer)">
                立即预约
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[9, 18, 27, 36]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 预约对话框 -->
    <el-dialog v-model="bookingDialogVisible" title="预约摄影师" width="500px">
      <el-form :model="bookingForm" label-width="100px">
        <el-form-item label="摄影师">
          <span>{{ selectedPhotographer?.name }}</span>
        </el-form-item>
        <el-form-item label="拍摄套餐">
          <el-select v-model="bookingForm.packageName" placeholder="请选择拍摄套餐">
            <el-option label="基础套餐 - ¥299" value="基础套餐" />
            <el-option label="标准套餐 - ¥599" value="标准套餐" />
            <el-option label="高级套餐 - ¥999" value="高级套餐" />
            <el-option label="豪华套餐 - ¥1999" value="豪华套餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="拍摄时间">
          <el-date-picker
            v-model="bookingForm.shootingTime"
            type="datetime"
            placeholder="选择拍摄时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="拍摄地点">
          <el-select v-model="bookingForm.shootingLocation" placeholder="请选择地址" filterable allow-create style="width: 100%;">
            <el-option v-for="addr in addressList" :key="addr.id" :label="addr.province + addr.city + addr.district + addr.detail" :value="addr.province + addr.city + addr.district + addr.detail" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bookingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBooking" :loading="bookingLoading">
          确认预约
        </el-button>
      </template>
    </el-dialog>

    <el-button type="success" @click="becomeDialogVisible = true" v-if="userStore.isLoggedIn && !isPhotographer">
      成为摄影师
    </el-button>

    <el-dialog v-model="becomeDialogVisible" title="申请成为摄影师" width="500px">
      <el-form :model="becomeForm" label-width="100px">
        <el-form-item label="真实姓名">
          <el-input v-model="becomeForm.realName" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="becomeForm.phone" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="becomeForm.intro" type="textarea" />
        </el-form-item>
        
      </el-form>
      <template #footer>
        <el-button @click="becomeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBecome" :loading="becoming">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import api from '../utils/api'

const router = useRouter()
const userStore = useUserStore()

interface Photographer {
  id: number
  name: string
  phone: string
  style: string
  intro: string
  workYears: number
  avatar: string
  authStatus: number
  availableSchedule: string
  createTime: string
  updateTime: string
  orderCount?: number
}

// 数据
const photographers = ref<Photographer[]>([])
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)
const loading = ref(false)

// 筛选条件
const filters = reactive({
  style: '',
  workYears: '',
  authStatus: null
})

// 预约相关
const bookingDialogVisible = ref(false)
const bookingLoading = ref(false)
const selectedPhotographer = ref<Photographer | null>(null)
const bookingForm = reactive({
  packageName: '',
  shootingTime: '',
  shootingLocation: ''
})

const becomeDialogVisible = ref(false)
const becoming = ref(false)
const becomeForm = reactive({
  realName: userStore.user?.realName || '',
  phone: userStore.user?.phone || '',
  intro: ''
})

const isPhotographer = ref(false)

const addressList = ref<any[]>([])

const fetchAddressList = async () => {
  if (!userStore.user?.id) return
  const res = await api.get(`/address/${userStore.user.id}`)
  addressList.value = res.data || []
}

const filteredPhotographers = computed(() => {
  let list = photographers.value
  if (filters.style) {
    list = list.filter(p => p.style?.includes(filters.style))
  }
  if (filters.workYears) {
    if (filters.workYears === '1-3') list = list.filter(p => p.workYears >= 1 && p.workYears <= 3)
    if (filters.workYears === '3-5') list = list.filter(p => p.workYears > 3 && p.workYears <= 5)
    if (filters.workYears === '5+') list = list.filter(p => p.workYears > 5)
  }
  if (filters.authStatus !== null && filters.authStatus !== undefined && filters.authStatus !== '') {
    list = list.filter(p => p.authStatus === filters.authStatus)
  }
  total.value = list.length
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  return list.slice(start, start + pageSize.value)
})

// 获取摄影师列表
const fetchPhotographers = async () => {
  try {
    loading.value = true
    // 这里调用后端API
    const res = await api.get('/photo/photographer/list')
    photographers.value = res.data || []
    total.value = photographers.value.length
  } catch (error) {
    console.error('获取摄影师列表失败:', error)
    ElMessage.error('获取摄影师列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPhotographers()
}

// 重置筛选
const resetFilters = () => {
  Object.assign(filters, {
    style: '',
    workYears: '',
    authStatus: null
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchPhotographers()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchPhotographers()
}

// 跳转到详情页
const goToDetail = (id: number) => {
  router.push(`/photographer/${id}`)
}

// 预约处理
const handleBook = (photographer: any) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push({ name: 'login' })
    return
  }
  selectedPhotographer.value = photographer
  bookingDialogVisible.value = true
  fetchAddressList()
}

// 提交预约
const submitBooking = async () => {
  if (!bookingForm.packageName || !bookingForm.shootingTime || !bookingForm.shootingLocation) {
    ElMessage.warning('请填写完整的预约信息')
    return
  }
  
  try {
    bookingLoading.value = true
    
    // 根据套餐名称确定价格
    const prices: Record<string, number> = {
      '基础套餐': 299,
      '标准套餐': 599,
      '高级套餐': 999,
      '豪华套餐': 1999
    }
    const totalPrice = prices[bookingForm.packageName] || 0

    const orderData = {
      userId: userStore.user?.id,
      photographerId: selectedPhotographer.value?.id,
      packageName: bookingForm.packageName,
      totalPrice: totalPrice,
      shootingTime: bookingForm.shootingTime,
      shootingLocation: bookingForm.shootingLocation,
      status: 'PENDING'
    }
    
    // 调试：打印将要发送的数据
    console.log('Sending order data:', orderData)

    // 调用后端API创建订单
    await api.post('/orders/user/create', orderData, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })
    
    ElMessage.success('预约成功！')
    bookingDialogVisible.value = false
    router.push('/orders')
  } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error('预约失败，请重试')
  } finally {
    bookingLoading.value = false
  }
}

const getAuthStatusText = (status: number) => {
  switch (status) {
    case 0: return '未认证'
    case 1: return '已认证'
    case 2: return '认证失败'
    default: return '未知'
  }
}

const getAuthStatusType = (status: number) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

const submitBecome = async () => {
  if (!becomeForm.realName || !becomeForm.phone) {
    ElMessage.warning('请填写完整信息')
    return
  }
  try {
    becoming.value = true
    await api.post('/application', {
      userId: userStore.user.id,
      realName: becomeForm.realName,
      phone: becomeForm.phone,
      intro: becomeForm.intro
    })
    ElMessage.success('申请已提交，请等待管理员审核')
    becomeDialogVisible.value = false
  } catch (e) {
    ElMessage.error('申请失败，请重试')
  } finally {
    becoming.value = false
  }
}

// 热门摄影师（按订单完成数排序，取前4名）
const hotPhotographers = computed(() => {
  return [...photographers.value]
    .sort((a, b) => (b.orderCount || 0) - (a.orderCount || 0))
    .slice(0, 4)
})

onMounted(async () => {
  fetchPhotographers()
  // // 判断当前用户是否为摄影师
  // if (!userStore.isLoggedIn || !userStore.user || !userStore.user.id) {
  //   isPhotographer.value = false
  //   return
  // }
  try {
    const res = await api.get(`/photo/photographer/byUser/${(userStore.user as any).id}`)
    isPhotographer.value = !!(res.data && res.data.data)
  } catch (e) {
    isPhotographer.value = false
  }
})
</script>

<style scoped>
.photographer-list {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 1.1rem;
}

.filter-card {
  margin-bottom: 30px;
}

.photographers-grid {
  margin-bottom: 40px;
}

.photographer-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
}

.photographer-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.photographer-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.photographer-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.photographer-info h3 {
  margin: 0 0 5px 0;
  color: #333;
}

.photographer-details {
  margin-bottom: 15px;
}

.photographer-style,
.photographer-years,
.photographer-phone,
.photographer-intro,
.photographer-available,
.photographer-auth,
.photographer-create,
.photographer-update {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 8px;
  color: #666;
}

.photographer-footer {
  text-align: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.hot-photographers {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px #f0f1f2;
  padding: 20px 24px;
}

.hot-photographer-card {
  text-align: center;
  cursor: pointer;
  transition: box-shadow 0.2s;
}

.hot-photographer-card:hover {
  box-shadow: 0 4px 16px #e0e6ed;
}

.hot-photographer-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 8px;
}
</style> 